import {observable as o, computed as c, action as a} from 'mobx';
import _ from 'lodash';
import axios from 'core/axios';
import RootStore from 'core/Store.js';
import request from 'core/request.js';
import Im from 'immutable';
import {browserHistory} from 'react-router';

class Store extends RootStore {
    constructor(args) {
        super(args);
    }

    @o visible = false;
    @o isUpdate = false;
    @o cover = '';//封面
    @o interior = '';//预览图
    @o floorPlan = '';//平面图
    @o uploadSuccessCover = '';//上传成功后的封面
    @o uploadSuccessInterior = '';//上传成功后的预览图
    @o uploadSuccessFloorPlan = '';//上传成功后的平面图
    @o floorPlanFile = '';//平面图文件
    @o interiorFile = '';//预览图文件
    @o coverFile = '';//base64生成的文件-->展馆封面文件
    // @o recordCoverFile = '';//记录原始封面文件
    @o isUpdateCover = false;//是否修改了封面
    @o isUpdateInterior = false;//是否修改了预览图
    @o isUpdateFloorPlan = false;//是否修改了平面图
    @o modelId = '';//展馆id
    @o areaSize = '';//面积
    @o modelName = '';//名称
    @o modelLength = '';//展线
    @o modelHeight = '';//高度
    @o recommendCount = '';//推荐作品数量
    @o type = 3;//模型类型
    @o modelDataHref = '';//链接  模型替换
    @o collisionDataHref = '';//链接  碰撞替换
    @o configId = '';//配置与哪个馆相同
    @o hidden = 0;
    @o configList = [];

    will() {

    }

    checkInput() {
        if (!this.cover) {
            this.stores.Message.showMessage(3, '展馆封面不能为空');
            return true;
        }
        if (!this.interior) {
            this.stores.Message.showMessage(3, '展馆预览图不能为空');
            return true;
        }
        if (!this.modelName || (!!this.modelName && !this.modelName.toString().trim())) {
            this.stores.Message.showMessage(3, '展馆名称不能为空');
            return true;
        }
        if (!this.areaSize || (!!this.areaSize && !this.areaSize.toString().trim())) {
            this.stores.Message.showMessage(3, '展馆面积不能为空');
            return true;
        }
        if (!this.modelLength || (!!this.modelLength && !this.modelLength.toString().trim())) {
            this.stores.Message.showMessage(3, '展馆展线不能为空');
            return true;
        }
        if (!this.modelHeight || (!!this.modelHeight && !this.modelHeight.toString().trim())) {
            this.stores.Message.showMessage(3, '展馆高度不能为空');
            return true;
        }
        if (!this.recommendCount || (!!this.recommendCount && !this.recommendCount.toString().trim())) {
            this.stores.Message.showMessage(3, '展馆推荐作品数量不能为空');
            return true;
        }
        if (!this.isUpdate && !this.configId) {
            this.stores.Message.showMessage(3, '请选择展馆配置（新馆需要有配置信息）');
            return true;
        }
        if (!this.isUpdate && !this.modelDataHref) {
            this.stores.Message.showMessage(3, '展馆模型链接不能为空（新馆需要有模型支持）');
            return true;
        }
    }

    confirmDialog() {
        if (this.checkInput()) {
            return;
        }
        let uploadCount = 0;
        let successCount = 0;
        if (this.isUpdateCover) {
            uploadCount++;
            this.stores.Frame.showLoading();
            request({
                url: $$.api('getPolicy'),
                method: 'get',
                data: {type: !!~global.window.location.origin.indexOf('manage-test') ? 3 : 4}
            }).then((res) => {
                //上传需要相关数据
                var {
                    accessid,
                    callback,
                    dir,
                    expire,
                    host,
                    policy,
                    signature,
                    prefix,
                } = res.data;
                //遍历文件数据
                var file = this.coverFile.file;
                let formData = new FormData();
                let md5 = this.modelName + '效果图.' + this.coverFile.file.name.split('.').pop();
                formData.append('name', this.coverFile.file.name);
                formData.append('key', encodeURI(dir + md5));
                formData.append('policy', policy);
                formData.append('OSSAccessKeyId', accessid);
                formData.append('success_action_status', '200');
                formData.append('callback', callback);
                formData.append('signature', signature);
                formData.append('file', file);
                //开始上传
                axios.post(host, formData).then((uploadRes) => {
                    successCount++;
                    this.uploadSuccessCover = uploadRes.data.data.modelCover;
                    if (uploadRes.data.code === $$.SEM.SUCCESS_CODE) {
                        successCount === uploadCount && this.updateInfo();
                    } else {
                        this.stores.Frame.hideLoading();
                        this.stores.Message.fire('message', {
                            type: $$.SEM.ERROR_TEXT,
                            text: uploadRes.message
                        });
                    }
                }).catch((uploadErr) => {
                    this.stores.Frame.hideLoading();
                    this.stores.Message.fire('message', {
                        type: $$.SEM.ERROR_TEXT,
                        text: uploadErr.message
                    });
                });
            }).catch(err => {
                this.stores.Frame.hideLoading();
                this.stores.Message.fire('message', {
                    type: $$.SEM.ERROR_TEXT,
                    text: err.message
                });

            });
        }

        if (this.isUpdateInterior) {
            uploadCount++;
            this.stores.Frame.showLoading();
            request({
                url: $$.api('getPolicy'),
                method: 'get',
                data: {type: !!~global.window.location.origin.indexOf('manage-test') ? 3 : 4}
            }).then((res) => {
                //上传需要相关数据
                var {
                    accessid,
                    callback,
                    dir,
                    expire,
                    host,
                    policy,
                    signature,
                    prefix,
                } = res.data;
                //遍历文件数据
                var file = this.interiorFile.file;
                let formData = new FormData();
                let md5 = this.modelName + '顶视图.' + this.interiorFile.file.name.split('.').pop();
                formData.append('name', this.interiorFile.file.name);
                formData.append('key', encodeURI(dir + md5));
                formData.append('policy', policy);
                formData.append('OSSAccessKeyId', accessid);
                formData.append('success_action_status', '200');
                formData.append('callback', callback);
                formData.append('signature', signature);
                formData.append('file', file);
                //开始上传
                axios.post(host, formData).then((uploadRes) => {
                    successCount++;
                    this.uploadSuccessInterior = uploadRes.data.data.modelCover;
                    if (uploadRes.data.code === $$.SEM.SUCCESS_CODE) {
                        successCount === uploadCount && this.updateInfo();
                    } else {
                        this.stores.Frame.hideLoading();
                        this.stores.Message.fire('message', {
                            type: $$.SEM.ERROR_TEXT,
                            text: uploadRes.message
                        });
                    }
                }).catch((uploadErr) => {
                    this.stores.Frame.hideLoading();
                    this.stores.Message.fire('message', {
                        type: $$.SEM.ERROR_TEXT,
                        text: uploadErr.message
                    });
                });
            }).catch(err => {
                this.stores.Frame.hideLoading();
                this.stores.Message.fire('message', {
                    type: $$.SEM.ERROR_TEXT,
                    text: err.message
                });

            });
        }

        if (this.isUpdateFloorPlan) {
            uploadCount++;
            this.stores.Frame.showLoading();
            request({
                url: $$.api('getPolicy'),
                method: 'get',
                data: {type: 5}
            }).then((res) => {
                //上传需要相关数据
                var {
                    accessid,
                    callback,
                    dir,
                    expire,
                    host,
                    policy,
                    signature,
                    prefix,
                } = res.data;
                //遍历文件数据
                var file = this.floorPlanFile.file;
                let formData = new FormData();
                let md5 = this.modelName + '平面图.' + this.floorPlanFile.file.name.split('.').pop();
                formData.append('name', this.floorPlanFile.file.name);
                formData.append('key', encodeURI(dir + md5));
                formData.append('policy', policy);
                formData.append('OSSAccessKeyId', accessid);
                formData.append('success_action_status', '200');
                formData.append('callback', callback);
                formData.append('signature', signature);
                formData.append('file', file);
                //开始上传
                axios.post(host, formData).then((uploadRes) => {
                    successCount++;
                    this.uploadSuccessFloorPlan = uploadRes.data.data.modelCover;
                    if (uploadRes.data.code === $$.SEM.SUCCESS_CODE) {
                        successCount === uploadCount && this.updateInfo();
                    } else {
                        this.stores.Frame.hideLoading();
                        this.stores.Message.fire('message', {
                            type: $$.SEM.ERROR_TEXT,
                            text: uploadRes.message
                        });
                    }
                }).catch((uploadErr) => {
                    this.stores.Frame.hideLoading();
                    this.stores.Message.fire('message', {
                        type: $$.SEM.ERROR_TEXT,
                        text: uploadErr.message
                    });
                });
            }).catch(err => {
                this.stores.Frame.hideLoading();
                this.stores.Message.fire('message', {
                    type: $$.SEM.ERROR_TEXT,
                    text: err.message
                });

            });
        }


        if (uploadCount === 0) {
            this.updateInfo();
        }

    }

    updateInfo() {
        this.stores.Frame.showLoading();
        request({
            url: this.isUpdate ? $$.api('modelsUpdate') : $$.api('modelsInsert'),
            method: 'post',
            data: {
                id: this.modelId || null,
                cover: this.uploadSuccessCover || null,
                interior: this.uploadSuccessInterior || null,
                floorPlan: this.uploadSuccessFloorPlan || null,
                name: this.modelName,
                space: this.areaSize + 'm²',
                modelLength: parseInt(this.modelLength),
                modelHigh: parseInt(this.modelHeight),
                recommendCount: parseInt(this.recommendCount),
                style: this.type,
                type: this.isUpdate ? null : 1,
                configId: this.configId || null,
                collision: this.collisionDataHref || null,
                data: this.modelDataHref || null,
                hidden: this.hidden
            }
        }).then(res => {
            this.stores.Frame.hideLoading();
            this.fire('modelConfig:update');
            this.closeDialog();
            this.stores.Message.showMessage(1, res.message);
        }).catch(err => {
            this.stores.Frame.hideLoading();
            this.stores.Message.showMessage(2, err.message);
        })
    }

    closeDialog() {
        this.visible = false;
        this.setToDefault();
    }

    setToDefault() {
        this.isUpdate = false;
        this.cover = '';//封面
        this.interior = '';//
        this.floorPlan = '';//
        this.coverFile = '';
        this.interiorFile = '';//
        this.floorPlanFile = '';//
        this.uploadSuccessCover = '';//上传成功后的封面
        this.uploadSuccessInterior = '';//
        this.uploadSuccessFloorPlan = '';//
        this.isUpdateFloorPlan = false;
        this.isUpdateInterior = false;
        this.isUpdateCover = false;//是否修改了封面
        this.areaSize = '';//面积
        this.modelName = '';//名称
        this.modelLength = '';//展线
        this.modelHeight = '';//高度
        this.recommendCount = '';//推荐作品数量
        this.modelId = '';//推荐作品数量
        this.type = 3;//模型类型
        this.modelDataHref = '';//链接  模型替换
        this.collisionDataHref = '';//链接  碰撞替换
        this.configId = '';//配置与哪个馆相同
        this.hidden = 0;
    }

    modelNameChange(v) {
        this.modelName = v;
    }

    areaSizeChange(v) {
        this.areaSize = v;
    }

    modelHeightChange(v) {
        this.modelHeight = v;
    }

    countChange(v) {
        this.recommendCount = v;
    }

    configChange(v) {
        this.configId = v;
    }

    modelLengthChange(v) {
        this.modelLength = v;
    }

    hiddenChange(v) {
        this.hidden = v;
    }

    typeChange(v) {
        this.type = v;
    }

    collisionDataHrefChange(v) {
        this.collisionDataHref = v;
    }


    modelDataHrefChange(v) {
        this.modelDataHref = v;
    }

    filesOnChange(e, refs) {
        e.preventDefault();
        let target = e.target;
        let files = target.files;
        this.isUpdateCover = true;
        this.coverFile = {
            thumb: URL.createObjectURL(files[0]),
            name: $$.utils.getFilename(files[0].name),
            file: files[0]
        };
        this.cover = this.coverFile.thumb;
        refs.value = '';
    }

    interiorFileOnChange(e, refs) {
        e.preventDefault();
        let target = e.target;
        let files = target.files;
        this.isUpdateInterior = true;
        this.interiorFile = {
            thumb: URL.createObjectURL(files[0]),
            name: $$.utils.getFilename(files[0].name),
            file: files[0]
        };
        this.interior = this.interiorFile.thumb;
        refs.value = '';
    }

    floorPlanFileOnChange(e, refs) {
        e.preventDefault();
        let target = e.target;
        let files = target.files;
        this.isUpdateFloorPlan = true;
        this.floorPlanFile = {
            thumb: URL.createObjectURL(files[0]),
            name: $$.utils.getFilename(files[0].name),
            file: files[0]
        };
        this.floorPlan = this.floorPlanFile.thumb;
        refs.value = '';
    }

    mount() {
        this.on('modelDialog:show', (data) => {
            this.visible = true;
            if (data) {
                this.isUpdate = true;
                this.modelId = data.id;
                this.modelName = data.name;
                this.cover = data.cover;
                this.interior = data.interior;
                this.floorPlan = data.floorPlan;
                this.areaSize = parseFloat(data.space);
                this.modelLength = data.modelLength;
                this.modelHeight = data.modelHigh;
                this.recommendCount = data.recommendCount;
                this.type = data.style;
                this.hidden = data.hidden;
            }
        });
        request({
            url: $$.api('getSelectModelList'),
        }).then(res => {
            res.data && res.data.map(item => {
                this.configList.push({value: item.id, label: item.name + '_id:' + item.id});
            });
        });
    }

}

export default Store;